package class1.echo;

import lombok.Data;

import java.io.*;
import java.net.Socket;

/**
 * 我有故事，你有酒么？
 * JKhaled created by yunqisong@foxmail.com 2017/8/29
 * FOR :EchoClient
 */
@Data
public class EchoClient {

    private Socket socket;

    private PrintWriter writer;

    private BufferedReader reader;

    public EchoClient(String host, int port) {
        try {
            socket = new Socket(host, port);
            System.out.println("连接服务器成功!");
        } catch (IOException e) {
            System.out.println("连接服务器失败!");
        }
    }

    /**
     * 获取写入流
     *
     * @param socket
     * @return
     */
    private PrintWriter getWriter(Socket socket) {
        try {
            OutputStream outputStream = socket.getOutputStream();
            return new PrintWriter(outputStream, true);
        } catch (IOException e) {
            System.out.println("获取PrintWriter错误");
            return null;
        }
    }

    /**
     * 获取缓冲读入流
     *
     * @param socket
     * @return
     */
    private BufferedReader getReader(Socket socket) {
        try {
            InputStream inputStream = socket.getInputStream();
            return new BufferedReader(new InputStreamReader(inputStream));
        } catch (IOException e) {
            System.out.println("获取BufferReader错误");
            return null;
        }
    }

    public void talk() {
        try {
            writer = getWriter(socket);
            reader = getReader(socket);
            BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
            String msg = null;
            while ((msg = localReader.readLine()) != null) {
                writer.println(msg);
                System.out.println(reader.readLine());
                if ("bye".equals(msg))
                    break;
            }
        } catch (IOException e) {
            System.out.println("出问题了！");
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new EchoClient("127.0.0.1", 9000).talk();
    }
}
